package com.three.common.message.base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.JsonPacket;
import com.three.api.protocol.Packet;
import com.three.protocol.BaseModule;

import java.util.HashMap;
import java.util.Map;

import static com.three.protocol.CommandEnum.Command.KICK;

/**
 * Created by mathua on 2017/5/25.
 */
public final class KickPlayerMessage extends BaseMessage {
    private String deviceId;
    private long playerId;

    public KickPlayerMessage(Packet message, Connection connection) {
        super(message, connection);
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        BaseModule.KickPlayer_11 bodyData = BaseModule.KickPlayer_11.parseFrom(body);
        deviceId = bodyData.getDeviceId();
        playerId = Long.valueOf(bodyData.getPlayerId());
    }

    @Override
    public byte[] encode() {
        BaseModule.KickPlayer_11.Builder builder = BaseModule.KickPlayer_11.newBuilder();
        builder.setDeviceId(deviceId);
        builder.setPlayerId(playerId);
        return builder.build().toByteArray();
    }

    public static KickPlayerMessage build(Connection connection) {
        if (connection.getSessionContext().isSecurity()) {
            return new KickPlayerMessage(new Packet(KICK), connection);
        } else {
            return new KickPlayerMessage(new JsonPacket(KICK), connection);
        }
    }

    @Override
    protected Map<String, Object> encodeJsonBody() {
        Map<String, Object> body = new HashMap<>(2);
        body.put("deviceId", deviceId);
        body.put("playerId", playerId);
        return body;
    }

    @Override
    public String toString() {
        return "KickPlayerMessage{" +
                "deviceId='" + deviceId + '\'' +
                ", playerId='" + playerId + '\'' +
                '}';
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public void setPlayerId(long playerId) {
        this.playerId = playerId;
    }
}
